package models

import (
	"context"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"go-chain-data/global"
	"go.mongodb.org/mongo-driver/bson"
)

type WatchAddressConfig struct {
	ChainId     uint   `bson:"chainId"`
	ChainName   string `bson:"chainName"`
	Address     string `bson:"address"`
	Token       string `bson:"token"`
	CallBackUrl string `bson:"callBackUrl"`
	UserId      string `bson:"userId"`
	PrivateKey  string `bson:"privateKey"`
	Timestamp   uint64 `bson:"timestamp" json:"timestamp"`
	IsDel       uint   `bson:"isDel" json:"isDel"`  //删除状态 0.未删除 1.已删除
	BusinessId  string `bson:"businessId" json:"-"` //业务id
}

// GetWatchAddressConfigList 获取全部数据 从mongodb中
func GetWatchAddressConfigList() ([]WatchAddressConfig, error) {
	WatchAddressConfigClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("watch_address_config")
	filter := bson.D{}
	var result []WatchAddressConfig
	cursor, err := WatchAddressConfigClient.Find(context.Background(), filter)
	if err != nil {
		return nil, err
	}
	for cursor.Next(context.Background()) {
		var watchAddressConfig WatchAddressConfig
		err := cursor.Decode(&watchAddressConfig)
		if err != nil {
			return nil, err
		}
		result = append(result, watchAddressConfig)
	}
	return result, nil
}

// IsWatchAddressEvent 检查是否是需要监听的地址交易
func IsWatchAddressEvent(log *types.Log) bool {
	// 获取需要监听的地址
	list, err := GetWatchAddressConfigList()
	if err != nil {
		return false
	}
	formAddress := common.HexToAddress(log.Topics[1].Hex()).String()
	toAddress := common.HexToAddress(log.Topics[2].Hex()).String()
	// 将log.Address转换为string
	logAddress := log.Address.String()
	// 遍历需要监听的地址
	for _, v := range list {
		// 如果token为空，只监听地址
		if v.Token == "" {
			if v.Address == formAddress || v.Address == toAddress {
				return true
			}
			continue
		} else {
			if (v.Address == formAddress || v.Address == toAddress) && v.Token == logAddress {
				return true
			}
		}
	}
	return false
}

// IsExistTxHash 根据txHash判断是否存在
func IsExistTxHash(txHash string) bool {
	WatchAddressInfoClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("watch_address_info")
	filter := bson.D{{"txHash", txHash}}
	count, err := WatchAddressInfoClient.CountDocuments(context.Background(), filter)
	if err != nil {
		return false
	}
	if count > 0 {
		return true
	}
	return false
}

// GetWatchAddressConfig 获取需要监听的地址详情
func GetWatchAddressConfig(formAddress string, toAddress string, token string) (WatchAddressConfig, error) {
	WatchAddressConfigClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("watch_address_config")
	filter := bson.D{
		{"$and", bson.A{
			bson.D{{"$or", bson.A{
				bson.D{{"address", formAddress}},
				bson.D{{"address", toAddress}},
			}}},
			bson.D{{"token", token}},
		}},
	}
	var result WatchAddressConfig
	err := WatchAddressConfigClient.FindOne(context.Background(), filter).Decode(&result)
	if err != nil {
		return WatchAddressConfig{}, err
	}
	return result, nil
}
